package school.xauat.inscription_sys.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import school.xauat.inscription_sys.pojo.vo.RespVo;
import school.xauat.inscription_sys.util.ImgFmtUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

import static school.xauat.inscription_sys.errorcode.ErrorCode.*;

/**
 * @author ：zsy
 * @date ：Created 2022/4/26 22:13
 * @description：
 */
@RestController
@RequestMapping("/image")
public class ImageController {

    @GetMapping(value = "/{imgName}")
    public void download(@PathVariable("imgName") String imgName,
                         HttpServletResponse response) throws IOException {
        InputStream in = null;
        try{
            //从minio文件服务器上获取图片流
            String path = ImgFmtUtil.projectImgPath + imgName;
            in = new FileInputStream(new File(path));
            response.setContentType("image/png");
            OutputStream out = response.getOutputStream();
            byte[] buff = new byte[1024];
            int rc = 0;
            while ((rc = in.read(buff, 0, 1024)) > 0) {
                out.write(buff, 0, rc);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(in != null)
            {
                in.close();
            }
        }
    }

    @PostMapping("/upload")
    public RespVo upload(@RequestParam(name = "image") MultipartFile image) {
        if (!ImgFmtUtil.isCorrect(image.getOriginalFilename())) {
            return RespVo.error(ERROR_IMAGE_FORMAT, getMsg(ERROR_IMAGE_FORMAT));
        }
        try {
            image.transferTo(new File(ImgFmtUtil.getImgStorePath(image)));
        } catch (IOException e) {
            e.printStackTrace();
            return RespVo.error(ERROR_IMAGE_SAVE_FAIL, getMsg(ERROR_IMAGE_SAVE_FAIL));
        }
        System.out.println(image.getOriginalFilename());
        return RespVo.ok(image.getOriginalFilename());
    }
}
